package com.yang.dao;

import com.yang.pojo.good;
import com.yang.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GoodDao {
    //根据品牌id查询商品信息
    public ArrayList<good> selectGoodByBrandId(int brandId) throws SQLException {
        ArrayList<good> goodList = new ArrayList<>();
        String sql = "SELECT good_id goodId,good_name goodName,good_img goodImg,good_cost goodCost,good_min_price goodMinPrice,good_first_price goodFirstPrice,good_second_price goodSecondPrice,good_third_price goodThirdPrice,good_forth_price goodForthPrice,good_fifth_price goodFifthPrice \n" +
                "FROM tb_brand,tb_brand_good,tb_good WHERE tb_brand.brand_id = tb_brand_good.fk_brand_id AND tb_brand_good.fk_good_id = tb_good.good_id AND tb_brand.brand_id = ?";
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        goodList = (ArrayList<good>) queryRunner.query(sql, new BeanListHandler<good>(good.class), brandId);
        return goodList;
    }

    //保存商品信息
    public int insertGood(String goodName,String goodImg,int goodMinPrice,int goodFifthPrice) throws SQLException {
        int  goodId = 0;
        String sql = "insert into tb_good(good_name,good_img,good_cost,good_min_price,good_first_price,good_second_price,good_third_price,good_forth_price,good_fifth_price) values(?,?,700,?,100,400,450,550,?)";
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        Object object = queryRunner.insert(sql, new ScalarHandler<>(), goodName, goodImg, goodMinPrice, goodFifthPrice);
        goodId = Integer.parseInt(String.valueOf(object));
        return goodId;
    }

    //保存商品和品牌的关联关系
    public int insertGoodAndBrand(int fkBrandId,int fkGoodId) throws SQLException {
        int i=0;
        String sql = "insert into tb_brand_good(fk_brand_id,fk_good_id) values(?,?) ";
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        i = queryRunner.update(sql, fkBrandId, fkGoodId);
        return i;

    }

    //保存商品与评估选项的关系
    public int insertGoodAndInfoDetail(int goodId,int infoDetailId,int price) throws SQLException {
        int i=0;
        String sql = "INSERT INTO tb_good_detail(fk_good_id,fk_info_detail_id,good_discount) VALUES(?,?,?)";
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        i = queryRunner.update(sql, goodId, infoDetailId, price);
        return i;
    }
}
